const storage = localStorage

const defaultSettings = {
  onlineSwitch: false,
  selectedChatModel: '' // 当前选中的对话模型
}

class CacheUnits {
  #key = '__xzai_user_settings__';
  #cache = null ;

  constructor () {
    this.listen()
  }

  get (k) {
    if (this.#cache === null) {
      this.init()
    }
    return this.#cache[k] === undefined ? defaultSettings[k] : this.#cache[k]
  }

  getAll () {
    return this.#cache
  }

  parse (v) {
    let val
    try {
      val = JSON.parse(v || JSON.stringify(defaultSettings))
    } catch (e) {
      val = {}
    }
    return val
  }

  init () {
    const val = storage.getItem(this.#key)
    this.#cache = this.parse(val)
  }

  set (v, val) {
    this.#cache[v] = val
    storage.setItem(this.#key, JSON.stringify(this.#cache))
  }

  clear () {
    Object.keys(this.#cache).forEach((k) => {
      // @ts-ignore
      this.#cache[k] = defaultSettings[k]
    })
    storage.removeItem(this.#key)
  }

  listen () {

  }
}

export default new CacheUnits()
